﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.Sql;
using System.Data.SqlClient;

public class CustomBDetail
{
    //din aspnet_User
    public string UserName { get; set; }
    public string UserId;
    //din Bookmark
    public decimal Index { get; set; }
    public string Titlu { get; set; }
    public string Link { get; set; }
    public string Owner { get; set; }
    public string Descriere { get; set; }
    public string Taguri { get; set; }
    public System.Nullable<int> Voturi { get; set; }
    //din Comments
    public string Message { get; set; }
}

public partial class LinqDetailedBookmark : System.Web.UI.Page
{
    // <<<<<<<<<<<paginarea repeaterului>>>>>>>>>>
    public int PageNumber
   {
      get
      {
         if (ViewState["PageNumber"] != null)
            return Convert.ToInt32(ViewState["PageNumber"]);
         else
            return 0;
      }
      set
      {
         ViewState["PageNumber"] = value;
      }
   }
   protected override void OnInit(EventArgs e)
   {
      base.OnInit(e);
      rptPages.ItemCommand +=
         new RepeaterCommandEventHandler(rptPages_ItemCommand);
   }
   private void LoadData()
   {
      SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.mdf;Integrated Security=True;User Instance=True");
      cn.Open();
      Decimal URIvar = System.Convert.ToDecimal(Request["id"]);
      SqlDataAdapter da = new SqlDataAdapter("SELECT aspnet_Users.UserName UserName, Comments.Message Message FROM Bookmark INNER JOIN Comments ON Bookmark.[Index] = Comments.Target INNER JOIN aspnet_Users ON Comments.UserName = aspnet_Users.UserName where Comments.Target = " + URIvar, cn);
      DataTable dt = new DataTable();
      da.Fill(dt);
      cn.Close();
      PagedDataSource pgitems = new PagedDataSource();
      DataView dv = new DataView(dt);
      pgitems.DataSource = dv;
      pgitems.AllowPaging = true;
      pgitems.PageSize = 5;
      pgitems.CurrentPageIndex = PageNumber;
      if (pgitems.PageCount > 1)
      {
         rptPages.Visible = true;
         ArrayList pages = new ArrayList();
         for (int i = 0; i < pgitems.PageCount; i++)
         pages.Add((i + 1).ToString());
         rptPages.DataSource = pages;
         rptPages.DataBind();
      }
      else
         rptPages.Visible = false;
      rptItems.DataSource = pgitems;
      rptItems.DataBind();
   }
   void rptPages_ItemCommand(object source, RepeaterCommandEventArgs e)
   {
      PageNumber = Convert.ToInt32(e.CommandArgument) - 1;
      LoadData();
   }
   // <<<<<<<<<<<paginarea repeaterului>>>>>>>>>>
    
    private Image GenerateThumb(String link)
    {
        WebsitesScreenshot.WebsitesScreenshot _WebsitesScreenshot = new WebsitesScreenshot.WebsitesScreenshot();
        WebsitesScreenshot.WebsitesScreenshot.Result _Result;
        Image ima = new Image();
        string path = null;
        path = Server.MapPath(".");
        _WebsitesScreenshot.ImageHeight = 160;
        _WebsitesScreenshot.ImageWidth = 160;
        _Result = _WebsitesScreenshot.CaptureWebpage("http://" + link);

        if (_Result == WebsitesScreenshot.WebsitesScreenshot.Result.Captured)
        {

            _WebsitesScreenshot.SaveImage(path + "\\" + link + ".jpg");
            ima.ImageUrl = link + ".jpg";
        }
        else if (_Result == WebsitesScreenshot.WebsitesScreenshot.Result.Failed)
        {
            Response.Write("");
            Response.Write("Failed");
        }
        else if (_Result == WebsitesScreenshot.WebsitesScreenshot.Result.Timeout)
        {
            Response.Write("");
            Response.Write("Timeout");
        }
        _WebsitesScreenshot.Dispose();
        return ima;
    }
    //  protected System.Web.UI.WebControls.Panel CurrentPanel;
    // CODEGEN: This call is required by the ASP.NET Web Form Designer.
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.Load += new System.EventHandler(this.Page_Load);
    }

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
    }
    bool contorpagina = false;
    //nu stiu ce are dar intra in page_load de 2 ori altfel
    protected void Page_Load(object sender, EventArgs e)
    {
        
        if (!contorpagina)
        {
            Decimal URIvar = System.Convert.ToDecimal(Request["id"]);
            LoadData();
            contorpagina = true;
            DataContext db = new DataContext("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\ASPNETDB.MDF;Integrated Security=True;User Instance=True;");
            Table<aspnet_User> aspnet_Users = db.GetTable<aspnet_User>();
            Table<Bookmark> Bookmarks = db.GetTable<Bookmark>();
            Table<Comment> Comments = db.GetTable<Comment>();
            IQueryable<CustomBDetail> BookmarkQuery = from s in aspnet_Users
                                                  join h in Bookmarks
                                                  on s.UserId equals h.Owner
                                                  where h.Index == URIvar
                                                  select new CustomBDetail { Titlu = h.Titlu, Link = h.Link, UserName = s.UserName, UserId = s.UserId, Owner = s.UserId, Index = h.Index, Taguri = h.Taguri, Descriere = h.Descriere, Voturi = h.Voturi };
            //SELECT [Titlu], [UserName], [Descriere], [Taguri], [Index] FROM [Bookmark] b join [aspnet_Users] a ON (b.Owner = a.UserId)
            foreach (CustomBDetail i in BookmarkQuery)
            {

                LTitlu.Text = i.Titlu + "\n ";
                LTitlu.Style.Value = "font-family: 'Myriad Pro Light'; font-size: x-large; font-variant: small-caps; color: #DBDBDB; font-weight: bold;";
                LLink.Text = i.Link;
                HyperLink2.NavigateUrl = "~/UserProfile.aspx?id="+ i.UserId;
                LOwner.Text = i.UserName;
                if(Page.User.Identity.Name!="")if (Page.User.Identity.Name != (i.UserName))
                {
                    LoginView2.FindControl("IdRemoveBookmark").Visible = false;
                }
                else LoginView2.FindControl("IdAddBookmark").Visible = false;
                LDescriere.Text = i.Descriere;
                //LVoturi.Text = i.Voturi + "";
                LTaguri.Text = i.Taguri;
                Imagine.ImageUrl = "screens\\"+i.Titlu.Replace('/','_') + ".jpg";
                Imagine.Style.Value = "position:relative;right60px;";
                IQueryable<CustomBDetail> CommentsQuery = from b in Comments
                                                      join c in Bookmarks on b.Target equals c.Index
                                                      join a in aspnet_Users on b.UserName equals a.UserName
                                                      where b.Target == URIvar
                                                      select new CustomBDetail { UserName = a.UserName, Message = b.Message };
                //SELECT [UserName], [Message] FROM [Comments] b
                //    join [aspnet_Users] a ON (b.UserID = a.UserId)
                //    join Bookmark c ON (c.[Index] = b.Target)
                //    where b.Target = URIvar;
               /* foreach (CustomBDetail s in CommentsQuery)
                {
                    Label LNume = new Label();
                    LNume.Text = " Name: " + s.UserName + "\n ";
                    LNume.Style.Value = "font-family: 'Myriad Pro Light'; font-size: x-large; font-variant: small-caps; color: #DBDBDB; font-weight: bold;";
                    Label LComment = new Label();
                    LComment.Text = " said: " + s.Message + "\n ";
                    Panel temp = new Panel();
                    temp.Controls.Add(LNume);
                    temp.Controls.Add(LComment);
                    MessagePanel.Controls.Add(temp);
                   
                }*/
            }
            //SqlMesaje.SelectCommand = "SELECT aspnet_Users.UserName UserName, Comments.Message Message FROM Bookmark INNER JOIN Comments ON Bookmark.[Index] = Comments.Target INNER JOIN aspnet_Users ON Comments.UserName = aspnet_Users.UserName where Comments.Target = " + URIvar;
        
        }
    }
    protected void Submit_Click(object sender, EventArgs e)
    {
        try
        {
            if (((TextBox)LoginView1.FindControl("elm1")).Text=="") { LInfo.Text = "Mesaj Obligatoriu"; return; }
            SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.mdf;Integrated Security=True;User Instance=True");
            TextBox txt = (TextBox)LoginView1.FindControl("elm1");

            string ins = "INSERT INTO Comments (UserName,Message,Target) VALUES (@user,@str2,@bookmarkindex)";
            con.Open();
            SqlCommand a = new SqlCommand(ins, con);
            a.Parameters.AddWithValue("user", LoginView1.Page.User.Identity.Name);
            a.Parameters.AddWithValue("str2", txt.Text);
            a.Parameters.AddWithValue("bookmarkindex", Request["id"]);
            a.ExecuteNonQuery();
            con.Close();
            Server.Transfer("~/Confirm.aspx?msg="+"Adaugarea comentariului");
        }
        catch (Exception er)
        {
            LInfo.Text = "EROARE " + er.Message;
        }
    }
    protected void Add_Click(object sender, EventArgs e)
    {
        try
        {
            SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.mdf;Integrated Security=True;User Instance=True");
            string ins = "INSERT INTO Bookmark (Titlu, Owner, Descriere, Taguri, Link) VALUES (@titlu,@owner,@descriere,@taguri,@link)";
            DataContext db = new DataContext("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\ASPNETDB.MDF;Integrated Security=True;User Instance=True;");
            Table<Bookmark> Bookmarks = db.GetTable<Bookmark>();
            IQueryable<CustomBDetail> BookmarkQuery = from h in Bookmarks
                                                  where h.Index == System.Convert.ToDecimal(Request["id"])
                                                  select new CustomBDetail { Titlu = h.Titlu, Owner= h.Owner, Link = h.Link, Index = h.Index, Taguri = h.Taguri, Descriere = h.Descriere, Voturi = h.Voturi };
            //SELECT Titlu, " + Page.User.Identity.Name + ", Descriere, Taguri, Link, Path, Voturi FROM Bookmark AS Bookmark_1 WHERE ([Index] = " + )
            con.Open();
            SqlCommand a = new SqlCommand(ins, con);
            foreach (CustomBDetail i in BookmarkQuery)
            {
                a.Parameters.AddWithValue("titlu", i.Titlu);
                a.Parameters.AddWithValue("descriere", i.Descriere);
                a.Parameters.AddWithValue("taguri", i.Taguri);
                a.Parameters.AddWithValue("link", i.Link);
            }
            Table<aspnet_User> user = db.GetTable<aspnet_User>();
            IQueryable<CustomBDetail> userquery = from h in user
                                                  where h.UserName == Page.User.Identity.Name
                                                  select new CustomBDetail {UserId =h.UserId};
            foreach (CustomBDetail i in userquery)
            {
                a.Parameters.AddWithValue("owner", i.UserId);
            }
            a.ExecuteNonQuery();
            con.Close();
            Server.Transfer("~/Confirm.aspx?msg=" + "Adaugarea Bookmarkului ");
        }
        catch (Exception er)
        {
            LInfo.Text = "EROARE " + er.Message;
        }
    }
    protected void Delete_Click(object sender, EventArgs e)
    {
        try
        {
            SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.mdf;Integrated Security=True;User Instance=True");
            string ins = "DELETE FROM Bookmark WHERE Bookmark.[Index] = "+ System.Convert.ToDecimal(Request["id"]) ;
            con.Open();
            SqlCommand a = new SqlCommand(ins, con);
            a.ExecuteNonQuery();
            con.Close();
            Server.Transfer("~/MyBookmarks.aspx");
        }
        catch (Exception er)
        {
            LInfo.Text = "EROARE " + er.Message;
        }
    }
}
